package summary;

import java.util.Stack;

/**
 * @Author: 海琳琦
 * @Date: 2022/3/13 15:13
 * https://leetcode-cn.com/problems/minimum-absolute-difference-in-bst/
 */
public class Title530 {

    static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        public TreeNode() {
        }

        public TreeNode(int val) {
            this.val = val;
        }

        public TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    public int getMinimumDifference(TreeNode root) {
        Stack<TreeNode> stack = new Stack<>();
        TreeNode pre = null;
        int min = Integer.MAX_VALUE;
        while (root != null || !stack.isEmpty()) {
            while (root != null) {
                stack.push(root);
                root = root.left;
            }
            root = stack.pop();
            if (pre != null && root.val - pre.val < min) {
                min = root.val - pre.val;
            }
            pre = root;
            root = root.right;
        }
        return min;
    }

    TreeNode pre = null;
    int min = Integer.MAX_VALUE;
    public int getMinimumDifference1(TreeNode root) {
        if (root.left != null) {
            getMinimumDifference1(root.left);
        }
        if (pre != null && root.val - pre.val < min) {
            min = root.val - pre.val;
        }
        pre = root;
        if (root.right != null) {
            getMinimumDifference1(root.right);
        }
        return min;
    }






    public int getMinimumDifference2(TreeNode root) {
        if (root == null) {
            return Integer.MAX_VALUE;
        }
        int left = getMinimumDifference2(root.left);
        int min;
        if (pre == null) {
            min = Integer.MAX_VALUE;
        }else{
            min = Math.min(left, root.val - pre.val);
        }
        pre = root;
        int right = getMinimumDifference2(root.right);
        return Math.min(min, right);
    }


    public static void main(String[] args) {

    }
}
